<?php
function sub_str($str, $length = 0, $append = true)
{
	$str = trim($str);
	$strlength = strlen($str);

	if ($length == 0 || $length >= $strlength)
	{
		return $str;
	}
	elseif ($length < 0)
	{
		$length = $strlength + $length;
		if ($length < 0)
		{
			$length = $strlength;
		}
	}

	if (function_exists('mb_substr'))
	{
		$newstr = mb_substr($str, 0, $length, 'utf-8');
	}
	elseif (function_exists('iconv_substr'))
	{
		$newstr = iconv_substr($str, 0, $length, 'utf-8');
	}
	else
	{
		//$newstr = trim_right(substr($str, 0, $length));
		$newstr = substr($str, 0, $length);
	}

	if ($append && $str != $newstr)
	{
		$newstr .= '...';
	}

	return $newstr;
}

function trim_right($str)
{
	$len = strlen($str);
	/* 为空或单个字符直接返回 */
	if ($len == 0 || ord($str{$len-1}) < 127)
	{
		return $str;
	}
	/* 有前导字符的直接把前导字符去掉 */
	if (ord($str{$len-1}) >= 192)
	{
		return substr($str, 0, $len-1);
	}
	/* 有非独立的字符，先把非独立字符去掉，再验证非独立的字符是不是一个完整的字，不是连原来前导字符也截取掉 */
	if (preg_match("/utf/i", 'utf-8'))
	{
		$r_len = strlen(rtrim($str, "\x80..\xBF"));
	}
	elseif (preg_match("/gb/i", 'utf-8'))
	{
		$r_len = strlen(rtrim($str, "\u4e00..\u9fa5"));
	}
	else
	{
		$r_len = strlen(rtrim($str, "\x80..\xBF"));
	}
	if ($r_len == 0 || ord($str{$r_len-1}) < 127)
	{
		return sub_str($str, 0, $r_len);
	}

	$as_num = ord(~$str{$r_len -1});
	if ($as_num > (1<<(6 + $r_len - $len)))
	{
		return $str;
	}
	else
	{
		return substr($str, 0, $r_len-1);
	}
}

function compile_str($str)
{
    $arr = array('<' => '＜', '>' => '＞');

    return strtr($str, $arr);
}

function hight_light($str, $keywords)
{
	if(!is_array($keywords))
	{
		$keywords = explode(" ", $keywords);
	}
	foreach($keywords as $key => $value)
	{
		if($value<>'')
		{
			$p = array("/\./si","/\//si","/\{/si","/\}/si","/\?/si","/\[/si","/\]/si","/\|/si","/\(/si","/\)/si");
			$r = array("\.","\/","\{","\}","\?","\[","\]","\|","\(","\)");
			$pattern[] = preg_replace($p, $r, addslashes($value));
		}
	}
	if(is_array($pattern))
	{
		$str = preg_replace("/(".implode("|", $pattern).")/si", "<font color=red>\\1</font>", $str);
	}
	return $str;
}

function str_len($str)
{
	$length = strlen(preg_replace('/[\x00-\x7F]/', '', $str));

	if ($length)
	{
		return strlen($str) - $length + intval($length / 3) * 2;
	}
	else
	{
		return strlen($str);
	}
}

function db_create_in($item_list, $field_name = '')
{
	if (empty($item_list))
	{
		return $field_name . " IN ('') ";
	}
	else
	{
		if (!is_array($item_list))
		{
			$item_list = explode(',', $item_list);
		}
		$item_list = array_unique($item_list);
		$item_list_tmp = '';
		foreach ($item_list AS $item)
		{
			if ($item !== '')
			{
				$item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
			}
		}
		if (empty($item_list_tmp))
		{
			return $field_name . " IN ('') ";
		}
		else
		{
			return $field_name . ' IN (' . $item_list_tmp . ') ';
		}
	}
}

function real_ip()
{
	static $realip = NULL;

	if ($realip !== NULL)
	{
		return $realip;
	}

	if (isset($_SERVER))
	{
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
		{
			$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

			/* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
			foreach ($arr AS $ip)
			{
				$ip = trim($ip);

				if ($ip != 'unknown')
				{
					$realip = $ip;

					break;
				}
			}
		}
		elseif (isset($_SERVER['HTTP_CLIENT_IP']))
		{
			$realip = $_SERVER['HTTP_CLIENT_IP'];
		}
		else
		{
			if (isset($_SERVER['REMOTE_ADDR']))
			{
				$realip = $_SERVER['REMOTE_ADDR'];
			}
			else
			{
				$realip = '0.0.0.0';
			}
		}
	}
	else
	{
		if (getenv('HTTP_X_FORWARDED_FOR'))
		{
			$realip = getenv('HTTP_X_FORWARDED_FOR');
		}
		elseif (getenv('HTTP_CLIENT_IP'))
		{
			$realip = getenv('HTTP_CLIENT_IP');
		}
		else
		{
			$realip = getenv('REMOTE_ADDR');
		}
	}

	preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
	$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

	return $realip;
}

function is_email($user_email)
{
	$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
	if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false)
	{
		if (preg_match($chars, $user_email))
		{
			return true;
		} else
		{
			return false;
		}
	} else
	{
		return false;
	}
}

function is_time($time)
{
	$pattern = '/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/';

	return preg_match($pattern, $time);
}

if (!function_exists('file_get_contents'))
{
	
	function file_get_contents($file)
	{
		if (($fp = @fopen($file, 'rb')) === false)
		{
			return false;
		}
		else
		{
			$fsize = @filesize($file);
			if ($fsize)
			{
				$contents = fread($fp, $fsize);
			}
			else
			{
				$contents = '';
			}
			fclose($fp);

			return $contents;
		}
	}
}

if (!function_exists('file_put_contents'))
{
	define('FILE_APPEND', 'FILE_APPEND');

	
	function file_put_contents($file, $data, $flags = '')
	{
		$contents = (is_array($data)) ? implode('', $data) : $data;

		if ($flags == 'FILE_APPEND')
		{
			$mode = 'ab+';
		}
		else
		{
			$mode = 'wb';
		}

		if (($fp = @fopen($file, $mode)) === false)
		{
			return false;
		}
		else
		{
			$bytes = fwrite($fp, $contents);
			fclose($fp);

			return $bytes;
		}
	}
}

if (!function_exists('floatval'))
{

	function floatval($n)
	{
		return (float) $n;
	}
}


function log_write($arg, $file = '', $line = '')
{
	if ((DEBUG_MODE & 4) != 4)
	{
		return;
	}

	$str = "\r\n-- ". date('Y-m-d H:i:s'). " --------------------------------------------------------------\r\n";
	$str .= "FILE: $file\r\nLINE: $line\r\n";

	if (is_array($arg))
	{
		$str .= '$arg = array(';
		foreach ($arg AS $val)
		{
			foreach ($val AS $key => $list)
			{
				$str .= "'$key' => '$list'\r\n";
			}
		}
		$str .= ")\r\n";
	}
	else
	{
		$str .= $arg;
	}

	file_put_contents(ROOT_PATH . '/log/log.txt', $str);
}

function make_dir($folder)
{
	$reval = false;

	if (!file_exists($folder))
	{
		/* 如果目录不存在则尝试创建该目录 */
		@umask(0);

		/* 将目录路径拆分成数组 */
		preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);

		/* 如果第一个字符为/则当作物理路径处理 */
		$base = ($atmp[0][0] == '/') ? '/' : '';

		/* 遍历包含路径信息的数组 */
		foreach ($atmp[1] AS $val)
		{
			if ('' != $val)
			{
				$base .= $val;

				if ('..' == $val || '.' == $val)
				{
					/* 如果目录为.或者..则直接补/继续下一个循环 */
					$base .= '/';

					continue;
				}
			}
			else
			{
				continue;
			}

			$base .= '/';

			if (!file_exists($base))
			{
				/* 尝试创建目录，如果创建失败则继续循环 */
				if (@mkdir(rtrim($base, '/'), 0777))
				{
					@chmod($base, 0777);
					$reval = true;
				}
			}
		}
	}
	else
	{
		/* 路径已经存在。返回该路径是不是一个目录 */
		$reval = is_dir($folder);
	}

	clearstatcache();

	return $reval;
}

function gzip_enabled()
{
	static $enabled_gzip = NULL;

	if ($enabled_gzip === NULL)
	{
		$enabled_gzip = function_exists('ob_gzhandler');
	}

	return $enabled_gzip;
}

function addslashes_deep($value)
{
	if (empty($value))
	{
		return $value;
	}
	else
	{
		//return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
		return is_array($value) ? array_map('addslashes_deep', $value) : htmlspecialchars($value);
	}
}

function addslashes_deep_obj($obj)
{
	if (is_object($obj) == true)
	{
		foreach ($obj AS $key => $val)
		{
			$obj->$key = addslashes_deep($val);
		}
	}
	else
	{
		$obj = addslashes_deep($obj);
	}

	return $obj;
}
function stripslashes_deep($value)
{
	if (empty($value))
	{
		return $value;
	}
	else
	{
		return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
	}
}


function make_semiangle($str)
{
	$arr = array('０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
	'５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
	'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
	'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
	'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
	'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
	'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
	'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
	'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
	'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
	'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
	'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
	'ｙ' => 'y', 'ｚ' => 'z',
	'（' => '(', '）' => ')', '〔' => '[', '〕' => ']', '【' => '[',
	'】' => ']', '〖' => '[', '〗' => ']', '“' => '[', '”' => ']',
	'‘' => '[', '’' => ']', '｛' => '{', '｝' => '}', '《' => '<',
	'》' => '>',
	'％' => '%', '＋' => '+', '—' => '-', '－' => '-', '～' => '-',
	'：' => ':', '。' => '.', '、' => ',', '，' => '.', '、' => '.',
	'；' => ',', '？' => '?', '！' => '!', '…' => '-', '‖' => '|',
	'”' => '"', '’' => '`', '‘' => '`', '｜' => '|', '〃' => '"',
	'　' => ' ');

	return strtr($str, $arr);
}

function mysql_like_quote($str)
{
	return strtr($str, array("\\\\" => "\\\\\\\\", '_' => '\_', '%' => '\%'));
}


function real_server_ip()
{
	static $serverip = NULL;

	if ($serverip !== NULL)
	{
		return $serverip;
	}

	if (isset($_SERVER))
	{
		if (isset($_SERVER['SERVER_ADDR']))
		{
			$serverip = $_SERVER['SERVER_ADDR'];
		}
		else
		{
			$serverip = '0.0.0.0';
		}
	}
	else
	{
		$serverip = getenv('SERVER_ADDR');
	}

	return $serverip;
}


function cbnet_header($string, $replace = true, $http_response_code = 0)
{
	if (strpos($string, '../upgrade/index.php') === 0)
	{
		echo '<script type="text/javascript">window.location.href="' . $string . '";</script>';
	}
	$string = str_replace(array("\r", "\n"), array('', ''), $string);

	if (preg_match('/^\s*location:/is', $string))
	{
		@header($string . "\n", $replace);

		exit();
	}

	if (empty($http_response_code) || PHP_VERSION < '4.3')
	{
		@header($string, $replace);
	}
	else
	{
		@header($string, $replace, $http_response_code);
	}
}

function cbnet_iconv($source_lang, $target_lang, $source_string = '')
{
	static $chs = NULL;

	/* 如果字符串为空或者字符串不需要转换，直接返回 */
	if ($source_lang == $target_lang || $source_string == '' || preg_match("/[\x80-\xFF]+/", $source_string) == 0)
	{
		return $source_string;
	}

	if ($chs === NULL)
	{
		require_once(ROOT_PATH . '/includes/cls_iconv.php');
		$chs = new Chinese(ROOT_PATH);
	}

	return $chs->Convert($source_lang, $target_lang, $source_string);
}

function cbnet_geoip($ip)
{
	static $fp = NULL, $offset = array(), $index = NULL;

	$ip    = gethostbyname($ip);
	$ipdot = explode('.', $ip);
	$ip    = pack('N', ip2long($ip));

	$ipdot[0] = (int)$ipdot[0];
	$ipdot[1] = (int)$ipdot[1];
	if ($ipdot[0] == 10 || $ipdot[0] == 127 || ($ipdot[0] == 192 && $ipdot[1] == 168) || ($ipdot[0] == 172 && ($ipdot[1] >= 16 && $ipdot[1] <= 31)))
	{
		return 'LAN';
	}

	if ($fp === NULL)
	{
		$fp = fopen(ROOT_PATH . '/public/ipdata.dat', 'rb');
		if ($fp === false)
		{
			return 'Invalid IP data file';
		}
		$offset = unpack('Nlen', fread($fp, 4));
		if ($offset['len'] < 4)
		{
			return 'Invalid IP data file';
		}
		$index  = fread($fp, $offset['len'] - 4);
	}

	$length = $offset['len'] - 1028;
	$start  = unpack('Vlen', $index[$ipdot[0] * 4] . $index[$ipdot[0] * 4 + 1] . $index[$ipdot[0] * 4 + 2] . $index[$ipdot[0] * 4 + 3]);
	for ($start = $start['len'] * 8 + 1024; $start < $length; $start += 8)
	{
		if ($index{$start} . $index{$start + 1} . $index{$start + 2} . $index{$start + 3} >= $ip)
		{
			$index_offset = unpack('Vlen', $index{$start + 4} . $index{$start + 5} . $index{$start + 6} . "\x0");
			$index_length = unpack('Clen', $index{$start + 7});
			break;
		}
	}

	fseek($fp, $offset['len'] + $index_offset['len'] - 1024);
	$area = fread($fp, $index_length['len']);

	fclose($fp);
	$fp = NULL;

	return $area;
}



function exception_handler($errno, $errstr, $errfile, $errline)
{
	return;
}


function dump($vars, $label = '', $return = false)
{
	if (ini_get('html_errors')) {
		$content = "<pre>\n";
		if ($label != '') {
			$content .= "<strong>{$label} :</strong>\n";
		}
		$content .= htmlspecialchars(print_r($vars, true));
		$content .= "\n</pre>\n";
	} else {
		$content = $label . " :\n" . print_r($vars, true);
	}
	if ($return) { return $content; }
	echo $content;
	return null;
}


function get_user_browser()
{
	if (empty($_SERVER['HTTP_USER_AGENT']))
	{
		return '';
	}

	$agent       = $_SERVER['HTTP_USER_AGENT'];
	$browser     = '';
	$browser_ver = '';

	if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs))
	{
		$browser     = 'Internet Explorer';
		$browser_ver = $regs[1];
		//dump($regs);
	}
	elseif (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs))
	{
		$browser     = 'FireFox';
		$browser_ver = $regs[1];
	}
	elseif (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs))
	{
		$browser     = 'Opera';
		$browser_ver = $regs[1];
	}
	elseif (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs))
	{
		$browser     = 'OmniWeb';
		$browser_ver = $regs[2];
	}
	elseif (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs))
	{
		$browser     = 'Netscape';
		$browser_ver = $regs[2];
	}
	elseif (preg_match('/safari\/([^\s]+)/i', $agent, $regs))
	{
		$browser     = 'Safari';
		$browser_ver = $regs[1];
	}
	elseif (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs))
	{
		$browser     = 'Lynx';
		$browser_ver = $regs[1];
	}

	if (preg_match('/Maxthon/i', $agent, $regs))
	{
		$browser     = '傲游 (IE ' .$browser_ver. ')';
		$browser_ver = '';
	}
	elseif (preg_match('/TencentTraveler/i', $agent, $regs))
	{
		$browser     = '腾讯TT (IE ' .$browser_ver. ')';
		$browser_ver = '';
	}
	elseif (preg_match('/360SE/i', $agent, $regs))
	{
		$browser     = '360安全浏览器 (IE ' .$browser_ver. ')';
		$browser_ver = '';
	}
	elseif (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs))
	{
		$browser     = '(Internet Explorer ' .$browser_ver. ') NetCaptor';
		$browser_ver = $regs[1];
	}

	if (preg_match('/Chrome\/([^\s]+)/i', $agent, $regs))
	{
		$browser     = '谷歌浏览器 (Chrome ' .$regs[1] . ')';
		$browser_ver = '';
	}

	if (!empty($browser))
	{
		return addslashes($browser . ' ' . $browser_ver);
	}
	else
	{
		return 'Unknow browser';
	}
}


function is_spider($record = true)
{
    static $spider = NULL;

    if ($spider !== NULL)
    {
        return $spider;
    }

    if (empty($_SERVER['HTTP_USER_AGENT']))
    {
        $spider = '';

        return '';
    }

    $searchengine_bot = array(
        'googlebot',
        'mediapartners-google',
        'baiduspider',
		'360spider',
		'360jk yunjiankong',
        'msnbot',
        'yodaobot',
        'yahoo! slurp;',
        'yahoo! slurp china;',
        'iaskspider',
        'sogou web spider',
        'sogou push spider',
		'bingbot',
		'easouspider',
		'ahrefsbot',
		'semrushbot'
    );

    $searchengine_name = array(
        'Google',
        'Google Adsense',
        '百度',
		'360搜索',
		'360云监控',
        'MSN',
        '有道',
        'YAHOO',
        'Yahoo China',
        'IASK',
        '搜狗',
        '搜狗',
		'Bing',
		'宜搜',
		'AhrefsBot',
		'SemrushBot'
    );

    $spider = strtolower($_SERVER['HTTP_USER_AGENT']);

    foreach ($searchengine_bot AS $key => $value)
    {
        if (strpos($spider, $value) !== false)
        {
            $spider = $searchengine_name[$key];

            if ($record === true)
            {
                $GLOBALS['db']->autoReplace('searchengine', array('date' => date('Y-m-d'), 'searchengine' => $spider, 'count' => 1), array('count' => 1));
            }

            return $spider;
        }
    }

    $spider = '';

    return '';
}

function get_os()
{
	if (empty($_SERVER['HTTP_USER_AGENT']))
	{
		return 'Unknown';
	}

	$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	$os    = '';

	if (strpos($agent, 'win') !== false)
	{
		if (strpos($agent, 'nt 5.1') !== false)
		{
			$os = 'Windows XP';
		}
		elseif (strpos($agent, 'nt 5.2') !== false)
		{
			$os = 'Windows 2003';
		}
		elseif (strpos($agent, 'nt 5.0') !== false)
		{
			$os = 'Windows 2000';
		}
		elseif (strpos($agent, 'nt 6.0') !== false)
		{
			$os = 'Windows Vista';
		}
		elseif (strpos($agent, 'nt 6.1') !== false)
		{
			$os = 'Windows 7';
		}
		elseif (strpos($agent, 'nt') !== false)
		{
			$os = 'Windows NT';
		}
		elseif (strpos($agent, 'win 9x') !== false && strpos($agent, '4.90') !== false)
		{
			$os = 'Windows ME';
		}
		elseif (strpos($agent, '98') !== false)
		{
			$os = 'Windows 98';
		}
		elseif (strpos($agent, '95') !== false)
		{
			$os = 'Windows 95';
		}
		elseif (strpos($agent, '32') !== false)
		{
			$os = 'Windows 32';
		}
		elseif (strpos($agent, 'ce') !== false)
		{
			$os = 'Windows CE';
		}
	}
	elseif (strpos($agent, 'linux') !== false)
	{
		$os = 'Linux';
	}
	elseif (strpos($agent, 'unix') !== false)
	{
		$os = 'Unix';
	}
	elseif (strpos($agent, 'sun') !== false && strpos($agent, 'os') !== false)
	{
		$os = 'SunOS';
	}
	elseif (strpos($agent, 'ibm') !== false && strpos($agent, 'os') !== false)
	{
		$os = 'IBM OS/2';
	}
	elseif (strpos($agent, 'mac') !== false && strpos($agent, 'pc') !== false)
	{
		$os = 'Macintosh';
	}
	elseif (strpos($agent, 'powerpc') !== false)
	{
		$os = 'PowerPC';
	}
	elseif (strpos($agent, 'aix') !== false)
	{
		$os = 'AIX';
	}
	elseif (strpos($agent, 'hpux') !== false)
	{
		$os = 'HPUX';
	}
	elseif (strpos($agent, 'netbsd') !== false)
	{
		$os = 'NetBSD';
	}
	elseif (strpos($agent, 'bsd') !== false)
	{
		$os = 'BSD';
	}
	elseif (strpos($agent, 'osf1') !== false)
	{
		$os = 'OSF1';
	}
	elseif (strpos($agent, 'irix') !== false)
	{
		$os = 'IRIX';
	}
	elseif (strpos($agent, 'freebsd') !== false)
	{
		$os = 'FreeBSD';
	}
	elseif (strpos($agent, 'teleport') !== false)
	{
		$os = 'teleport';
	}
	elseif (strpos($agent, 'flashget') !== false)
	{
		$os = 'flashget';
	}
	elseif (strpos($agent, 'webzip') !== false)
	{
		$os = 'webzip';
	}
	elseif (strpos($agent, 'offline') !== false)
	{
		$os = 'offline';
	}
	else
	{
		$os = 'Unknown';
	}

	return $os;
}


function remove_url($body, $cfg_basehost)
{
	$basehost = "http://".$_SERVER['HTTP_HOST'];
	$body = str_replace("http://".$cfg_basehost,'#basehost#',$body);
	$body = str_replace($basehost,'#2basehost2#',$body);
	$body = preg_replace("/(<a[ \t\r\n]{1,}href=[\"']{0,}http:\/\/[^\/]([^>]*)>)|(<\/a>)/isU","",$body);
	$body = str_replace('#basehost#',$cfg_basehost,$body);
	$body = str_replace('#2basehost2#',$basehost,$body);
}

function update_file_info($tmp_id, $type, $id)
{
	$sql = "UPDATE `upload_files` SET `tmp_id`='',`id`='".$id."' WHERE `type`='".$type."' AND `tmp_id`='".$tmp_id."';";
	$GLOBALS['db']->query($sql);
}


function del_editor_file($cate, $id)
{
	$sql = "SELECT `url` FROM `upload_files` WHERE `cate`='".$cate."' AND `id`='".$id."';";
	$row = $GLOBALS['db']->getAll($sql);

	foreach($row AS $key=>$val)
	{
		@unlink(ROOT_PATH . $val['url']);
		//echo ROOT_PATH . $val['url'];
	}
	$sql = "DELETE FROM `upload_files` WHERE `cate`='".$cate."' AND `id`='".$id."';";
	$GLOBALS['db']->query($sql);
}


function ofc_max_plus($num)
{
	$num = floor($num);
	$l = strlen($num);
	if($l>1)
	{
		if($l>3)
		{
			for($i=$l;$i>=3;$i--)
			{
				$f = pow(10, $i-1);
				$t = substr($num, $l-$i, 1);
				$r += $t*$f;
			}
			$r += 100;
		}
		elseif ($l==3)
		{
			$r = substr($num, 0, 1)*100 + substr($num, 1, 1)*10 + 10;
		}
		else
		{
			$f = pow(10, $l-1);
			$r = ceil($num/$f)*$f;
		}
	}
	else
	{
		$r = 10;
	}
	return  $r;
}

function get_domain($url)
{
	$pattern = "/[\w-]+\.(com|net|org|gov|cc|biz|info|cn)(\.(cn|hk))*/";
	preg_match($pattern, $url, $matches);
	if(count($matches) > 0) {
		return $matches[0];
	}else{
		$rs = parse_url($url);
		$main_url = $rs["host"];
		if(!strcmp(long2ip(sprintf("%u",ip2long($main_url))),$main_url)) {
			return $main_url;
		}else{
			$arr = explode(".",$main_url);
			$count=count($arr);
			$endArr = array("com", "net", "org");//com.cn net.cn 等情况
			if (in_array($arr[$count-2],$endArr)){
				$domain = $arr[$count-3].".".$arr[$count-2].".".$arr[$count-1];
			}else{
				$domain = $arr[$count-2].".".$arr[$count-1];
			}
			return $domain;
		}
	}
}


function check_ip($ip, $ip_arr)
{
	$flag = false;
	//为空，不限制
	if(empty($ip_arr))
	{
		return true;
	}
	else 
	{
		foreach($ip_arr as $key => $val)
		{
			if(preg_match('/^'.$val.'/i', $ip))
			{
				$flag = true;
			}
		}
		return $flag;
	}
}



function send_mail($name_from,$email_to,$subject,$emailtext,$email_from,$receive_member_id,$web_administrators_id=0,$type='',$send_type=0,$info_id=0) {
global $serviceid;
include_once(ROOT_PATH . '/includes/PHPMailer/class.phpmailer.php');
$mail = new PHPMailer;
$mail->IsSMTP();                                      // Set mailer to use SMTP
	$mail->Host = 'smtp.qiye.163.com';  // Specify main and backup server;hwsmtp.exmail.qq.com
	$mail->Port = 465;
	$mail->SMTPAuth = true;                               // Enable SMTP authentication
	$mail->Username = 'kf@evan.com.cn';                            // SMTP username
	$mail->Password = 'Ez1x2c3v4'; 
	$mail->SMTPSecure = 'ssl';                            // Enable encryption, 'ssl' also accepted
	$mail->CharSet = "UTF-8";   // 这里指定字符集！
	$mail->Encoding = "base64";  
	$mail->From = 'kf@evan.com.cn';
	

$mail->FromName = $name_from;
$email_toArr=array();
$email_toArr=explode(",",$email_to);
$email_toArr=array_unique($email_toArr);
if($email_toArr[0]<>"")$mail->AddAddress($email_toArr[0]);  // Add a recipient
if($email_toArr[1]<>"")$mail->AddAddress($email_toArr[1]);  // Add a recipient
if($email_toArr[2]<>"")$mail->AddAddress($email_toArr[2]);  // Add a recipient
if($email_toArr[3]<>"")$mail->AddAddress($email_toArr[3]);  // Add a recipient
if($email_toArr[4]<>"")$mail->AddAddress($email_toArr[4]);  // Add a recipient
if($email_toArr[5]<>"")$mail->AddAddress($email_toArr[5]);  // Add a recipient
if($email_toArr[6]<>"")$mail->AddAddress($email_toArr[6]);  // Add a recipient



$mail->AddReplyTo($email_from);

//$mail->IsHTML(false);                                  // Set email format to HTML
$mail->IsHTML(true);

$mail->Subject = $subject;
$mail->Body = $emailtext;

$res=$mail->Send();

if($res){
	return true;
}
else return false;
}


function send_mail_tt($name, $email, $subject, $content, $type = 0, $notification=false)
{
    $shop_name = "五联";
    if ($GLOBALS['_CFG']['mail_service'] == 0 && function_exists('mail'))
    {
        $content_type = ($type == 0) ? 'Content-Type: text/plain; charset=utf-8' : 'Content-Type: text/html; charset=utf-8';
        $headers = array();
		$headers[] = 'MIME-Version: 1.0';
		$headers[] = $content_type . '; format=flowed';
        $headers[] = 'From: =?UTF-8?B?' . base64_encode($shop_name) . '?='.' <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        if ($notification)
        {
            $headers[] = 'Disposition-Notification-To: ' . '=?UTF-8?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        }

        $res = @mail($email, '=?UTF-8?B?'.base64_encode($subject).'?=', $content, implode("\r\n", $headers));

        if (!$res)
        {
            //$GLOBALS['err'] ->add($GLOBALS['_LANG']['sendemail_false']);
            return false;
        }
        else
        {
            return true;
        }
    }
    else
    {
        /* 邮件的头部信息 */
        $content_type = ($type == 0) ?
            'Content-Type: text/plain; charset=utf-8' : 'Content-Type: text/html; charset=utf-8';
        $content   =  base64_encode($content);

        $headers = array();
        $headers[] = 'Date: ' . gmdate('D, j M Y H:i:s') . ' +0000';
        $headers[] = 'To: "' . '=?UTF-8?B?' . base64_encode($name) . '?=' . '" <' . $email. '>';
        $headers[] = 'From: "' . '=?UTF-8?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        $headers[] = 'Subject: ' . '=?UTF-8?B?' . base64_encode($subject) . '?=';
        $headers[] = $content_type . '; format=flowed';
        $headers[] = 'Content-Transfer-Encoding: base64';
        $headers[] = 'Content-Disposition: inline';
        if ($notification)
        {
            $headers[] = 'Disposition-Notification-To: ' . '=?UTF-8?B?' . base64_encode($shop_name) . '?='.'" <' . $GLOBALS['_CFG']['smtp_mail'] . '>';
        }

        /* 获得邮件服务器的参数设置 */
        $params['host'] = $GLOBALS['_CFG']['smtp_host'];
        $params['port'] = $GLOBALS['_CFG']['smtp_port'];
        $params['user'] = $GLOBALS['_CFG']['smtp_user'];
        $params['pass'] = $GLOBALS['_CFG']['smtp_pass'];

        if (empty($params['host']) || empty($params['port']))
        {
            // 如果没有设置主机和端口直接返回 false
            //$GLOBALS['err'] ->add($GLOBALS['_LANG']['smtp_setting_error']);

            return false;
        }
        else
        {
            // 发送邮件
            if (!function_exists('fsockopen'))
            {
                //如果fsockopen被禁用，直接返回
                //$GLOBALS['err']->add($GLOBALS['_LANG']['disabled_fsockopen']);

                return false;
            }

            include_once(ROOT_PATH . 'includes/cls_smtp.php');
            static $smtp;

            $send_params['recipients'] = $email;
            $send_params['headers']    = $headers;
            $send_params['from']       = $GLOBALS['_CFG']['smtp_mail'];
            $send_params['body']       = $content;

            if (!isset($smtp))
            {
                $smtp = new smtp($params);
            }

            if ($smtp->connect() && $smtp->send($send_params))
            {
                return true;
            }
            else
            {
                $err_msg = $smtp->error_msg();
                if (empty($err_msg))
                {
                    //$GLOBALS['err']->add('Unknown Error');
                }
                else
                {
                    if (strpos($err_msg, 'Failed to connect to server') !== false)
                    {
                        //$GLOBALS['err']->add(sprintf($GLOBALS['_LANG']['smtp_connect_failure'], $params['host'] . ':' . $params['port']));
                    }
                    else if (strpos($err_msg, 'AUTH command failed') !== false)
                    {
                        //$GLOBALS['err']->add($GLOBALS['_LANG']['smtp_login_failure']);
                    }
                    elseif (strpos($err_msg, 'bad sequence of commands') !== false)
                    {
                        //$GLOBALS['err']->add($GLOBALS['_LANG']['smtp_refuse']);
                    }
                    else
                    {
                        //$GLOBALS['err']->add($err_msg);
                    }
                }

                return false;
            }
        }
    }
}

function yjt_id($id)
{
	if($id=='')
	{
		return '该规格不存在';
	}
	else
	{
		return str_pad($id, 6, '0', STR_PAD_LEFT);
	}
}

function yjt_sku($id)
{
	if($id=='')
	{
		return '该规格不存在';
	}
	else
	{
		return str_pad($id, 6, '0', STR_PAD_LEFT);
	}
}

function get_xy_id($v)
{
	if($v=='0')
	{
		$id = '0';
	}
	else
	{
		$sql = "SELECT `spec_id` FROM `product_spec` WHERE `name`='".$v."';";
		$id = $GLOBALS['db']->getOne($sql);
	}
	return $id;
}

function price_format($price, $with_y = true, $decimals=3)
{
    if($price==='')
    {
    	$price=0;
    }
	$price = number_format($price, $decimals, '.', '');
    if (substr($price, -1) == '.')
    {
     	$price = substr($price, 0, -1);
    }
	
    if ($with_y)
    {
		return sprintf("￥%s", $price);
		//return sprintf("￥%s元", $price);
    }
    else
    {
        return $price;
    }
}

function price_show($gg, $unit='个', $decimals=3)
{
	$str = '';
	$n = $p = array();
	$n[0] = $gg['num'];
	$n[1] = $gg['num1'];
	$n[2] = $gg['num2'];
	$p[0] = $gg['price'];
	$p[1] = $gg['price1'];
	$p[2] = $gg['price2'];
	$param_unit = $unit==''?'个':$unit;
	
	//单只，没有梯度的情况下
	if($n[0]==1 && $n[1]==0 && $n[2]==0)
	{
		$str = '<span class="price2">'.price_format($p[0], true, $decimals).'/'.$param_unit.'</span>';
	}
	else
	{
		$str = '<div><ul>';
		for ($i=0; $i<3; $i++)
		{
			if($n[$i] && $p[$i])
			{
				$str .= '<li>'.($n[$i+1]?($n[$i].'-'.($n[$i+1]-1)):"&ge;".$n[$i]).'个:<span class="price">'.price_format($p[$i], false).'</span>元/个</li>';
			}
		}
		$str .= '</ul></div>';
	}
	return $str;
}
function price_show_small($gg, $unit='个', $decimals=3)
{
	$str = '';
	if($gg['price']>0) $str = '<span class="price2">'.price_format($gg['price'], true, $decimals).'元/个</span>';
	else $str = '下单后报价';
	if($gg['price1']>0) $str = '<span class="price2">'.price_format($gg['price1'], true, $decimals).'元/个</span>起';
	if($gg['price2']>0) $str = '<span class="price2">'.price_format($gg['price2'], true, $decimals).'元/个</span>起';
	return $str;
}


function price_show_excel($gg)
{
	$n = $p = array();
	$n[0] = $gg['num'];
	$n[1] = $gg['num1'];
	$n[2] = $gg['num2'];
	$p[0] = $gg['price'];
	$p[1] = $gg['price1'];
	$p[2] = $gg['price2'];
	
	$str = '';
	for ($i=0; $i<3; $i++)
    {
		if($n[$i] && $p[$i])
		{
			$str .= $str==""?"":"\n";
			$str .= ($n[$i+1]?($n[$i].'-'.($n[$i+1]-1)):">".$n[$i]).'个:'.price_format($p[$i], false).'元/个';
		}
	}
	return $str;
}

function stock_show($gg)
{
	$stock = $gg['stock'];
	$delivery = $gg['delivery']>0?$gg['delivery'].'天左右' : '准现货';
	return $stock>0?'现货':$delivery;
}

function cart_goods($sess_id, $isCar = 0)
{
    $cart_goods = array();

    if ($isCar){
        $sql = "SELECT * FROM `cart` WHERE `session_id`='".$sess_id."' ORDER BY `add_tm` desc;";
    }else{
        $sql = "SELECT * FROM `cart` WHERE `price` > 0 AND `session_id`='".$sess_id."' ORDER BY `add_tm` desc;";
    }
    $cart_goods = $GLOBALS['db']->getAll($sql);

    return $cart_goods;
}


function get_order_sn()
{
    /* 选择一个随机的方案 */
    mt_srand((double) microtime() * 1000000);

    return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
}
function order_fee($goods)
{
    $total  = array(
        'goods_price'      => 0,//产品总价，更加数量和单价计算总和
        'shipping_fee'     => 0,//配送费，后续根据重量计算
        'pay_fee'          => 0,//支付手续费，后续计算
        'pack_fee'         => 0,//包装费，后期计算
        'discount'         => 0,//折扣金额
        'weight'           => 0,//总重量
        'volume'           => 0,//总体积
		'total_num'		   => 0,//产品总数量
		'total_fee'		   => 0,//总金额
    );
    //$weight = 0;

    /* 商品总价 */
	if(!empty($goods))
	{
		foreach ($goods AS $val)
		{
			$total['goods_price']  += $val['price'] * $val['pcount'];
			$total['total_num']  += $val['pcount'];
		}
	}
	else
	{
		$total['goods_price'] = 0;
	}
	//价格显示处理,显示成统一格式
	$total['goods_price'] = price_format($total['goods_price'], false, 2);

    $total['shipping_fee'] = $total['goods_price']>500?0:30;
	$total['total_fee'] = $total['goods_price']+$total['shipping_fee']+$total['pay_fee']+$total['pack_fee']-$total['discount'];
	
    return $total;
}

function send_sms_ali($member_mobile,$verify_array=array('')) {
if(!$verify_array[0]) return false;
//生成时间参数开始
date_default_timezone_set('GMT');
$Timestamp=date("Y-m-d")."T".date("H:i:s")."Z".'<br>';
date_default_timezone_set('PRC');
//生成时间参数结束
$random=mt_rand(1000000000, 9999999999);//生成随机数
$system_counttime_begin=array_sum(explode(" ", microtime())); //程序执行开始时间
$parameter_array=array(
	'SignatureMethod'=>'HMAC-SHA1',
	'SignatureNonce'=>$system_counttime_begin.$random,
	'AccessKeyId'=>'LTAI4Fm7GPKUBVZQPCuABsMj',
	'SignatureVersion'=>'1.0',
	'Timestamp'=>$Timestamp,
	'Format'=>'JSON',
	'Action'=>'SendSms',
	'Version'=>'2017-05-25',
	'RegionId'=>'cn-hangzhou',
	'PhoneNumbers'=>$member_mobile,
	'SignName'=>'五联塑料件',
	'TemplateParam'=>'{"code":"'.$verify_array[0].'"}',
	'TemplateCode'=>'SMS_176070188'
	);
ksort($parameter_array);//数组根据索引排序
//生成参数字串
$parameter_str=str_replace(array('+','*','%7E'),array('%20','%2A','~'),http_build_query($parameter_array));
//生成待签名字串
$sign_str="GET&%2F&".str_replace(array('+','*','%7E'),array('%20','%2A','~'),urlencode($parameter_str));
//生成签名
$Signature=base64_encode(hash_hmac('sha1', $sign_str,'GDbmhVxlT8kMBPSGsbfb9geNcht8NK'.'&', true));
//编码签名
$Signature=str_replace(array('+','*','%7E'),array('%20','%2A','~'),urlencode($Signature));
$url="http://dysmsapi.aliyuncs.com/?Signature=".$Signature."&".$parameter_str;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$ret = curl_exec($curl);
//解析结果
$ret_array=json_decode($ret,true);
$temp=$ret_array['Code'];//返回(ok)即为发送成功
if($temp=='OK') return true; else return false;
}


function send_sms($mobile, $content)
{
    $content = iconv('UTF-8', 'GB2312', trim($content));   
	$url="http://210.5.158.31/hy?uid=80467&auth=".md5('cbowlcbowl01')."&mobile=".$mobile."&msg=".urlencode($content)."&expid=0";
	$temp=file_get_contents($url);
	$temp=substr($temp,0,2)=='0,'?'0':$temp;
	return $temp==0 ? true : false;
}
function G($start, $end='', $dec=4) {
    static $_info       =   array();
    static $_mem        =   array();
    $memory_limit_on = function_exists('memory_get_usage');
    if(is_float($end)) { // 记录时间
        $_info[$start]  =   $end;
    }elseif(!empty($end)){ // 统计时间和内存使用
        if(!isset($_info[$end])) $_info[$end]       =  microtime(TRUE);
        if($memory_limit_on && $dec=='m'){
            if(!isset($_mem[$end])) $_mem[$end]     =  memory_get_usage();
            return number_format(($_mem[$end]-$_mem[$start])/1024);
        }else{
            return number_format(($_info[$end]-$_info[$start]),$dec);
        }

    }else{ // 记录时间和内存使用
        $_info[$start]  =  microtime(TRUE);
        if($memory_limit_on) $_mem[$start]           =  memory_get_usage();
    }
}

//记录访问统计
function tongji()
{
	$url = $_SERVER['REQUEST_URI'];
	$from_url = $_SERVER['HTTP_REFERER'];
	$user_agent = $_SERVER['HTTP_USER_AGENT'];
	$ip = real_ip();
	
	$sql = "INSERT INTO `ztest_tongji_log` SET `url`='".$url."',`from_url`='".$from_url."',`user_agent`='".$user_agent."',`ip`='".$ip."', `tm`=NOW();";
	//$GLOBALS['db']->query($sql);
	
}

//url传递安全化
function base_encode($str) {
        $src  = array("/","+","=");
        $dist = array("_a","_b","_c");
        $old  = base64_encode($str);
        $new  = str_replace($src,$dist,$old);
        return $new;
}

function base_decode($str) {
        $src = array("_a","_b","_c");
        $dist  = array("/","+","=");
        $old  = str_replace($src,$dist,$str);
        $new = base64_decode($old);
        return $new;
}